<template>
  <div class="main block block_column">
    <a-tabs v-model:activeKey="activeKey" class="tabs-fill-height">
      <a-tab-pane key="1" tab="运维笔记">
        <div class="row w100 h100">
          <NoteList
            :source="noteInfoList"
            @onRemove="handleRemove"
            @onNoteClick="handleEdit"
            @onNew="handleNew"
          /><Editor @onSave="handleContentSave" ref="editor" />
        </div>
      </a-tab-pane>
      <a-tab-pane key="2" tab="问答" force-render>
        <chat-component />
      </a-tab-pane>
      <a-tab-pane key="3" tab="构建配置">
        <a-button type="primary" @click="handleBuildChroma"
          >构建知识库</a-button
        >
      </a-tab-pane>
    </a-tabs>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, shallowRef } from "vue";
import { map } from "lodash";
import { ChatComponent, Editor, NoteList } from "./components";
import type { NoteInfo } from "@/models";
import useNotes from "./hooks/noteHooks";

const noteInfoList = ref<Array<NoteInfo>>([]);
const editor = ref(null);
const noteId = shallowRef("");

const { saveContent, getNoteTitles, removeContent, buildChroma, getMarkdown } =
  useNotes();

const loadNoteTitles = async () => {
  const { list } = await getNoteTitles();
  noteInfoList.value = map(list, (item) => ({
    title: item.title,
    id: item.id,
  }));
};

const handleEdit = async ({ id }) => {
  noteId.value = id;
  editor.value.loadContent(await getMarkdown({ id }));
};

// 新建
const handleNew = () => {
  noteId.value = "";
  editor.value.loadContent("");
};

const reloadNoteTitles = async () => {
  noteInfoList.value = [];
  await loadNoteTitles();
};

const handleRemove = async ({ id }) => {
  await removeContent({ id });
  await reloadNoteTitles();
};

const handleBuildChroma = async () => {
  await buildChroma();
};

const handleContentSave = async (content) => {
  const result = await saveContent({ id: noteId.value, content });
  reloadNoteTitles();
};

const text = ref("# Hello Editor");
const activeKey = ref("1");

onMounted(async () => {
  await loadNoteTitles();
});
</script>

<style lang="scss">
html,
body,
#app {
  height: 100%;
  margin: 0;
}

.list_container {
  width: 200px;
  height: 100%;
}
.editor_container {
  flex: 1;
}
.main {
  height: 100%; /* Ensure the main container takes full height */
  display: flex;
  flex-direction: column; /* Ensure children stack vertically */
  flex-grow: 1;
}
.ant-tabs-content {
  height: 100%;
}
.tabs-fill-height {
  flex: 1; /* Make the tabs take the remaining height */
  display: flex;
  flex-direction: column; /* Ensure tab panes stack vertically (if needed) */
}

.ant-tabs-tabpane {
  flex: 1; /* Ensure tab panes take full height of the tabs container */
  overflow-y: auto; /* Add vertical scrolling if content overflows */
}
</style>
